<?php 
defined('BASEPATH') OR exit('No direct script access allowed');

define('URL_SEPARATOR', '/');
define('TBL_UPLOKING_FILE', 'default_uploking_files');
define('TBL_UPLOKING_FOLDER', 'default_uploking_folders');
define('TBL_UPLOKING_RATING', 'default_uploking_ratings');
define('TBL_UPLOKING_USER', 'default_uploking_users');
define('TBL_UPLOKING_DOWNLOAD', 'default_uploking_downloads');
define('TBL_UPLOKING_WITHDRAWAL', 'default_uploking_withdrawals');
define('TBL_UPLOKING_COUNTRIES', 'default_uploking_countries');
define('TBL_UPLOKING_PACKAGES', 'default_uploking_packages');
define('TBL_UPLOKING_USER_PACKAGES', 'default_uploking_user_packages');

define('DATE_FORMAT','d-m-Y');
define('ACTIVE_ACCOUNT_EMAIL_TEMPLATE_SLUG','active-email-template-slug');
define('DOWNLOAD_VALID_TIME', 24);
define('DOWNLOAD_STATUS_INVALID', 0);
define('DOWNLOAD_STATUS_VALID', 1);
define('DOWNLOAD_STATUS_PAID', 2);

//Withdrawal status
define('WITHDRAWAL_PENDDING', 0);
define('WITHDRAWAL_PAID', 1);

//Good voting mark
define('RATING_GOOD_MARK', 4);
define('RATING_MARK_MIN', 1000); // 1000
define('RATING_MARK_PERCENT', 80); // 80
define('RATING_EXTRA_PERCENT', 10);
define('DOWNLOAD_TIME_CALCULATION', 1000);

//PACKAGE_STATUS
define('PACKAGE_STATUS_USED', 0);
define('PACKAGE_STATUS_PENDDING', 1);
define('PACKAGE_STATUS_CURRENT', 2);

function getAllRequestWithdrawMoney($userId){
	$ci = &get_instance();
	$withdrawalList = $ci->db->where('user_id', $userId)->get(TBL_UPLOKING_WITHDRAWAL)->result();
	if($withdrawalList){
		$money = 0;
		foreach ($withdrawalList as $withdrawal) {
			$money += $withdrawal->money;
		}
		return $money;
	}else{
		return 0;
	}
}

function getWithdrawedMoney($userId){
	$ci = &get_instance();
	$withdrawalList = $ci->db->where('status', WITHDRAWAL_PAID)->where('user_id', $userId)->get(TBL_UPLOKING_WITHDRAWAL)->result();
	if($withdrawalList){
		$money = 0;
		foreach ($withdrawalList as $withdrawal) {
			$money += $withdrawal->money;
		}
		return $money;
	}else{
		return 0;
	}
}

function getEarnedMoney($userId){
	$ci = &get_instance();
	$user = $ci->db->where('id', $userId)->get(TBL_UPLOKING_USER)->result();
	if(!$user){
		return 0;
	}
	$downloadedFileList = $ci->db->where('user_id', $userId)->where('status', DOWNLOAD_STATUS_VALID)->order_by('download_time', 'ASC')->get(TBL_UPLOKING_DOWNLOAD)->result();
	if($downloadedFileList){
		$userCountry = $ci->db->where('code', $user[0]->country_code)->get(TBL_UPLOKING_COUNTRIES)->result();
		if($userCountry){
			$userGroup = $userCountry[0]->group_id;
		}else{
			$userGroup = 4;
		}
		
		$money = 0;
		$capacity = 0;
		$i =0;
		//print_r(fileSizeInfo(1073741823));
		
		foreach ($downloadedFileList as $downloadedFile){
			if(($i > 0 && $i % DOWNLOAD_TIME_CALCULATION == 0) || ($i == count($downloadedFileList) - 1)){
				$fileSize = fileSizeInfo($capacity);
				if($userGroup == 1){
					if($fileSize[1] == 'GB'){
						$money += 40;
					}else if($fileSize[1] == 'MB'){
						if($fileSize[0] * 100 > 50000){
							$money += 35;
						}else if($fileSize[0] * 100 > 25000){
							$money += 30;
						}else if($fileSize[0] * 100 > 10000){
							$money += 25;
						}else if($fileSize[0] * 100 > 5000){
							$money += 20;
						}else if($fileSize[0] * 100 > 100){
							$money += 10;
						}
					}
				}else if($userGroup == 2){
					if($fileSize[1] == 'GB'){
						$money += 30;
					}else if($fileSize[1] == 'MB'){
						if($fileSize[0] * 100 > 50000){
							$money += 25;
						}else if($fileSize[0] * 100 > 25000){
							$money += 20;
						}else if($fileSize[0] * 100 > 10000){
							$money += 15;
						}else if($fileSize[0] * 100 > 5000){
							$money += 10;
						}else if($fileSize[0] * 100 > 100){
							$money += 5;
						}
					}
				}else if($userGroup == 3){
					if($fileSize[1] == 'GB'){
						$money += 25;
					}else if($fileSize[1] == 'MB'){
						if($fileSize[0] * 100 > 50000){
							$money += 20;
						}else if($fileSize[0] * 100 > 25000){
							$money += 15;
						}else if($fileSize[0] * 100 > 10000){
							$money += 10;
						}else if($fileSize[0] * 100 > 5000){
							$money += 5;
						}else if($fileSize[0] * 100 > 100){
							$money += 3;
						}
					}
				}else if($userGroup == 4){
					if($fileSize[1] == 'GB'){
						$money += 15;
					}else if($fileSize[1] == 'MB'){
						if($fileSize[0] * 100 > 50000){
							$money += 10;
						}else if($fileSize[0] * 100 > 25000){
							$money += 5;
						}else if($fileSize[0] * 100 > 10000){
							$money += 3;
						}else if($fileSize[0] * 100 > 5000){
							$money += 2;
						}else if($fileSize[0] * 100 > 100){
							$money += 1;
						}
					}	
				}
				//echo $money;
				//print_r($fileSize);
				$capacity = 0;	
			}else{
				$fileData = $ci->db->where('user_id', $userId)->where('id', $downloadedFile->file_id)->get(TBL_UPLOKING_FILE)->result();
				if($fileData){
					$capacity += $fileData[0]->filesize;
				}
			}
			$i++;
		}
		$numberOfVoting = getNumberOfVoting($userId);
		$numberOfGoodVoting = getNumberOfGoodVoting($userId);
		
		if($numberOfVoting > RATING_MARK_MIN && round($numberOfGoodVoting/$numberOfVoting * 100) > RATING_MARK_PERCENT){
			$money = round((100 + RATING_EXTRA_PERCENT) * $money/100);
		}
		return $money;
	}else{
		return 0;
	}
}

//Get number of voting
function getNumberOfVoting($userId){
	$ci = &get_instance();
	return $ci->db->where('user_id', $userId)->count_all_results(TBL_UPLOKING_RATING);
}

function getNumberOfGoodVoting($userId){
	$ci = &get_instance();
	return $ci->db->where('user_id', $userId)->where('rating >=', RATING_GOOD_MARK)->count_all_results(TBL_UPLOKING_RATING);
}


// Get forder name for each day
function uploking_getFolderName(){
	return date("Ymd");
}

function getCurrentPackage($userId){
	$ci = &get_instance();
	$currentUserPackage = $ci->db->where('status', PACKAGE_STATUS_CURRENT)->where('user_id', $userId)->get(TBL_UPLOKING_USER_PACKAGES)->result();
	if($currentUserPackage && ($currentUserPackage[0]->end_date < time())){
		$currentPackage = $ci->db->where('id', $currentUserPackage[0]->package_id)->get(TBL_UPLOKING_PACKAGES)->result();
		
		if($currentPackage){
			return $currentPackage[0];
		}else{
			return null;	
		}
	}else{
		if($penddingUserPackage = getUserPenddingPackage($userId, 'ASC')){
			$ci->db->set('status',PACKAGE_STATUS_CURRENT);
			$ci->db->where('id', $penddingUserPackage->id)->update(TBL_UPLOKING_USER_PACKAGES);
			$currentPackage = $ci->db->where('id', $penddingUserPackage->package_id)->get(TBL_UPLOKING_PACKAGES)->result();
			if($currentPackage){
				return $currentPackage[0];
			}else{
				return null;	
			} 
		}else{
			return null;
		}
	}
}
function getUserPenddingPackage($userId, $order){
	$ci = &get_instance();
	$penddingUserPackage = $ci->db->where('status', PACKAGE_STATUS_PENDDING)->where('user_id', $userId)->order_by('end_date', $order)->get(TBL_UPLOKING_USER_PACKAGES)->result();
	if($penddingUserPackage){
		return $penddingUserPackage[0];
	}else{
		return null;
	}
}

function getNextMonthTimeStamp($startTimeStamp, $months){
	$startDate = date('Y-m-d', $startTimeStamp);
	$nextDate = date('Y-m-d',strtotime("$startDate + $months months"));
	return strtotime($nextDate);
}
function getNextDayTimeStamp($startTimeStamp, $days){
	$startDate = date('Y-m-d', $startTimeStamp);
	$nextDate = date('Y-m-d',strtotime("$startDate + $days days"));
	return strtotime($nextDate);
}

function getCaptcha(){
	$ci = &get_instance();
	$ci->load->helper('captcha');
	$captchaWord = get_rand_string();
	$vals = array(
	    'word' => $captchaWord,
	    'img_path' => './uploads/default/captcha/',
	    'img_url' => site_url().'uploads/default/captcha/',
	    'font_path' => './uploads/default/captcha/fonts/TimesNewRomanBold.ttf',
	    'img_width' => '150',
	    'img_height' => 30,
	    //'expiration' => 7200
	    'expiration' => 200
	    );
	$timeLIMIT = 720;
	$captcha = array( 'captcha_exprise_time'=>time() + $timeLIMIT , 'captcha_content'=>$captchaWord );
	$ci = &get_instance();
	$ci->session->set_userdata($captcha);
	$cap = create_captcha($vals);
	return $cap['image'];
}
function get_rand_string($length = 5){
	$chars = 'ABCDEFGHKLMNOPQRSTWXYZabcdefghjkmnpqrstwxyz0123456789';
	$max = strlen($chars)-1;
	$string = '';
	mt_srand((double)microtime() * 1000000);
	while (strlen($string) < $length)
	{
		$string .= $chars{mt_rand(0, $max)};
	}
	return $string;
}
function fileSizeInfo($size){
	$unit = null;
	$units = array('B', 'KB', 'MB', 'GB', 'TB');

	for($i = 0, $c = count($units); $i < $c; $i++)
	{
		if ($size > 1024)
		{
			$size = $size / 1024;
		}
		else
		{
			$unit = $units[$i];
			break;
		}
	}

	//return round($size, 2).$sep.$unit;
	return array(
		0	=> round($size, 2),
		1	=> $unit
	);
}